<template>
  <div class="app-content-wrap" :style="'minHeight:' + gHeight + 'px;'">
    <div class="g-content-title">{{ pageTitle }}</div>

    <el-form
      :model="userObj"
      :rules="rules"
      ref="userModifyForm"
      label-width="80px"
      size="small"
    >
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="用户名" prop="userId">
            <el-input
              v-model="userObj.userId"
              placeholder="用户名"
              :readonly="ifReadonly"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="userObj.password"
              type="password"
              maxlength="20"
              placeholder="密码"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="工号">
            <el-input v-model="userObj.jobNbr" placeholder="工号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="userName">
            <el-input v-model="userObj.userName" placeholder="姓名"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="电话" prop="userPhone">
            <el-input
              v-model="userObj.userPhone"
              placeholder="固定电话（带区号）"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobile">
            <el-input
              v-model="userObj.mobile"
              maxlength="11"
              placeholder="手机号码"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="userEmail">
            <el-input v-model="userObj.userEmail" placeholder="邮箱"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="管理模块">
            <el-select v-model="moduleArray">
              <el-option label="全部" value=""></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12">
          <!--//角色-->
          <el-form-item label="角色" prop="userRole">
            <SelectRole
              :selectModel="userObj.userRole"
              @onRoleChange="onRoleChange"
            ></SelectRole>
          </el-form-item>
        </el-col>
        <!--//部门-->
        <el-col :span="12" v-show="showSelectDept">
          <el-form-item label="所属" prop="deptId">
            <SelectArea
              class="select__area"
              :selectModel="userObj.deptId"
              :areaIds="areaIds"
              @onAreaChange="onAreaChange"
              :roleId="userObj.userRole"
            ></SelectArea>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="15">
        <el-form-item style="padding-left:7px;">
          <el-button type="primary" size="small" @click="modifyUser()"
            >提交</el-button
          >
        </el-form-item>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import SelectArea from '../../components/common/select/area.vue'
import SelectRole from '../../components/common/select/role.vue'
import { validPhone, validTel, checkPassword } from '../../assets/scripts/base/validate.js'
import md5 from 'md5'

let rulePhone = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    if (!validPhone(value)) {
      callback(new Error('请输入正确的手机号码！'))
    } else {
      callback()
    }
  }
}

let ruleTel = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    if (!validTel(value)) {
      callback(new Error('请输入正确的固定电话号码！'))
    } else {
      callback()
    }
  }
}

let validPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (checkPassword(value)) {
      callback(new Error(checkPassword(value)))
    } else {
      callback()
    }
  }
}

export default {
  name: 'userModify',
  data () {
    return {
      gHeight: this.$store.state.gHeight,
      ifReadonly: true, // 用户名是否readOnly
      moduleArray: [],
      oldPassword: '', // 旧密码
      userObj: {
        userId: '',
        deptId: '',
        userRole: '',
        mobile: '',
        userName: '',
        userEmail: '',
        password: '',
        userPhone: '',
        jobNbr: ''
      },
      areaIds: {
        areaId1: '',
        areaId2: '',
        areaId3: ''
      },
      rules: {
        userId: [
          { required: true, message: '用户编号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: validPassword, trigger: ['blur'] }
        ],
        userPhone: [
          { validator: ruleTel, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: rulePhone, trigger: 'blur' }
        ],
        userEmail: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        userRole: [
          { required: true, message: '角色不能为空', trigger: ['blur'] }
        ],
        deptId: [
          { required: true, message: '所属不能为空', trigger: ['blur'] }
        ]
      },
      pageTitle: '',
      showSelectDept: false // 显示隐藏所属下拉菜单
      // tempRoleName: '' // 缓存角色名
    }
  },
  methods: {
    // 提交修改用户
    modifyUser () {
      if (this.$route.params.userId === 'addUser') {
        this.rules.password = [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: validPassword, trigger: 'blur' }
        ]
        this.insertUser()
      } else {
        let postPassword = ''
        /*    if (this.userObj.password === this.oldPassword) { // 没改密码的情况
              postPassword = this.userObj.password
              this.rules.password = [{ required: true, message: '密码不能为空', trigger: 'blur' }]
            } else { // 改密码的情况
              postPassword = md5(this.userObj.password)
              this.rules.password = [
                { required: true, message: '密码不能为空', trigger: 'blur' },
                { validator: this.validPassword, trigger: 'blur' }]
            } */
        if (this.userObj.password === '') { // 没改密码的情况
          postPassword = ''
          this.rules.password = []
        } else { // 改密码的情况
          postPassword = md5(this.userObj.password)
          this.rules.password = [
            { validator: validPassword, trigger: 'blur' }
          ]
        }
        let data = {
          userId: this.$route.params.userId,
          userRole: this.userObj.userRole,
          userName: this.userObj.userName,
          userPhone: this.userObj.userPhone,
          userEmail: this.userObj.userEmail,
          password: postPassword,
          mobile: this.userObj.mobile,
          jobNbr: this.userObj.jobNbr,
          deptId: this.userObj.deptId
        }
        let queryData = {
          userId: this.$route.params.userId,
          userName: this.userObj.userName,
          mobile: this.userObj.mobile,
          userRole: this.userObj.userRole,
          deptId1: this.areaIds.areaId1,
          deptId2: this.areaIds.areaId2,
          deptId3: this.areaIds.areaId3
        }
        let url = this.$base.getUrl('updateUserInfo')

        this.$refs['userModifyForm'].validate((valid) => {
          if (valid) {
            this.$store.dispatch('postForm', {
              url: url,
              data: data
            }).then(res => {
              if (res.code === 0) {
                this.$message({
                  type: 'success',
                  message: '修改成功！'
                })
                this.$router.push({
                  name: 'userList',
                  query: queryData
                })
              } else {
                this.$message.error('抱歉修改失败！')
              }
            })
          } else {
            return false
          }
        })
      }
    },
    // 新增用户
    insertUser () {
      let url = this.$base.getUrl('addUserInfo')

      this.$refs['userModifyForm'].validate((valid) => {
        if (valid) {
          this.$store.dispatch('postForm', {
            url: url,
            data: {
              userId: this.userObj.userId,
              userRole: this.userObj.userRole,
              userName: this.userObj.userName,
              userPhone: this.userObj.userPhone,
              userEmail: this.userObj.userEmail,
              // password: md5(this.userObj.password),
              password: md5(this.userObj.password, 32),

              mobile: this.userObj.mobile,
              jobNbr: this.userObj.jobNbr,
              deptId: this.userObj.deptId,
              userState: '1'
            }
          }).then(res => {
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '添加成功！'
              })
              this.$router.push({
                name: 'userList'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 初始获取用户信息
    getUser () {
      let url = this.$base.getUrl('selectUserInfoByPrimaryKey')
      this.$store.dispatch('getForm', {
        url: url,
        data: {
          userId: this.$route.params.userId
        }
      }).then(res => {
        // console.log(res)
        if (res) {
          this.userObj.userId = res.userId
          this.areaIds.areaId1 = res.deptId1 ? res.deptId1 : ''
          this.areaIds.areaId2 = res.deptId2 ? res.deptId2 : ''
          this.areaIds.areaId3 = res.deptId3 ? res.deptId3 : ''

          this.userObj.deptId = res.deptId
          this.userObj.userRole = res.userRole
          this.userObj.mobile = res.mobile
          this.userObj.userName = res.userName
          this.userObj.userEmail = res.userEmail
          this.userObj.password = res.password
          this.oldPassword = res.password // 保存旧密码
          this.userObj.userPhone = res.userPhone
        } else {
          this.$message.error('拉取用户信息失败')
        }
      })
    },
    // role组件change时
    onRoleChange (val) {
      this.userObj.userRole = val
      if (this.userObj.userRole === 1 || !this.userObj.userRole) {
        this.showSelectDept = false
        this.rules.deptId = []
      } else {
        this.showSelectDept = true
        this.rules.deptId = [{ required: true, message: '所属不能为空', trigger: ['blur'] }]
      }
    },
    // area组件change时
    onAreaChange (val) {
      this.userObj.deptId = val
    }
  },
  mounted () {
    if (this.$route.params.userId === 'addUser') {
      this.ifReadonly = false
      this.pageTitle = '人员新增'
    } else {
      this.getUser()
      this.pageTitle = '人员编辑'
    }
  },
  components: {
    SelectArea,
    SelectRole
  },
  beforeRouteLeave (to, from, next) {
    if (to.name !== 'userList') {
      this.$store.commit('keepOut')
    }
    next()
  }
}
</script>

<style scoped>
.select__area /deep/ .select__street {
  padding: 0 !important;
}
.select__area /deep/ .select__community {
  padding-right: 0 !important;
}
.select__area /deep/ .select__department {
  padding-right: 0 !important;
}
</style>
